import dicomParser from 'dicom-parser';
// 加载读取数文件
export class DicomProcessor {
    constructor() {
        this.dicomParser = dicomParser;
    }

    async processFiles(files) {
        const seriesGroups = new Map();
        const processedFiles = [];
        const skippedFiles = [];

        for (const file of files) {
            try {
                const dicomData = await this.parseDicomFile(file);
                if (dicomData) {
                    processedFiles.push(dicomData);
                } else {
                    skippedFiles.push({ file: file.name, reason: '无法创建图像数据' });
                }
            } catch (error) {
                console.warn(`跳过文件 ${file.name}:`, error.message);
                skippedFiles.push({ file: file.name, reason: error.message });
            }
        }

        // 如果没有成功处理任何文件，抛出错误
        if (processedFiles.length === 0) {
            const errorMessage = skippedFiles.length > 0 
                ? `无法处理任何DICOM文件。跳过的文件：\n${skippedFiles.map(f => `${f.file}: ${f.reason}`).join('\n')}`
                : '未找到有效的DICOM文件';
            throw new Error(errorMessage);
        }

        // 按序列分组
        this.groupBySeries(processedFiles, seriesGroups);

        // 对每个序列的图像进行排序
        seriesGroups.forEach(series => {
            this.sortSeriesImages(series);
        });

        // 如果有跳过的文件，在控制台显示警告
        if (skippedFiles.length > 0) {
            console.warn(`成功处理 ${processedFiles.length} 个文件，跳过 ${skippedFiles.length} 个文件：`, skippedFiles);
        }

        return seriesGroups;
    }

    async parseDicomFile(file) {
        return new Promise((resolve, reject) => {
            // 添加文件大小检查
            const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
            if (file.size > MAX_FILE_SIZE) {
                reject(new Error(`文件 ${file.name} 太大 (${(file.size / 1024 / 1024).toFixed(2)}MB)，超过限制 (${MAX_FILE_SIZE / 1024 / 1024}MB)`));
                return;
            }

            const reader = new FileReader();
            
            reader.onload = (event) => {
                try {
                    const arrayBuffer = event.target.result;
                    const byteArray = new Uint8Array(arrayBuffer);
                    
                    // 检查是否为有效的DICOM文件
                    if (!this.isDicomFile(byteArray)) {
                        reject(new Error(`文件 ${file.name} 不是有效的DICOM文件`));
                        return;
                    }
                    
                    // 检查 dicom-parser 是否可用
                    if (!this.dicomParser || typeof this.dicomParser.parseDicom !== 'function') {
                        throw new Error('dicom-parser 库未正确加载或不可用');
                    }

                    // 直接在主线程中解析，避免 Web Worker 的问题
                    try {
                        const dataSet = this.dicomParser.parseDicom(byteArray);
                        
                        // 检查解析结果
                        if (!dataSet || !dataSet.elements) {
                            throw new Error('DICOM解析失败，未获得有效的数据集');
                        }
                        
                        // 验证DICOM数据集
                        this.validateDicomFile(dataSet);
                        
                        const dicomData = this.extractDicomData(dataSet, file);
                        dicomData.imageData = this.createImageData(dataSet);
                        dicomData.file = file;
                        dicomData.arrayBuffer = arrayBuffer;
                        
                        // 如果没有窗宽窗位信息，根据像素值范围自动计算
                        if (dicomData.imageData && (!dicomData.windowWidth || !dicomData.windowCenter)) {
                            const { minPixelValue, maxPixelValue } = dicomData.imageData;
                            if (minPixelValue !== undefined && maxPixelValue !== undefined) {
                                if (!dicomData.windowWidth) {
                                    dicomData.windowWidth = maxPixelValue - minPixelValue;
                                }
                                if (!dicomData.windowCenter) {
                                    dicomData.windowCenter = (maxPixelValue + minPixelValue) / 2;
                                }
                            }
                        }
                        
                        resolve(dicomData);
                    } catch (error) {
                        reject(new Error(`解析文件 ${file.name} 失败: ${error.message}`));
                    }
                } catch (error) {
                    reject(new Error(`解析文件 ${file.name} 失败: ${error.message}`));
                }
            };
            
            reader.onerror = () => {
                reject(new Error(`读取文件 ${file.name} 失败`));
            };
            
            reader.readAsArrayBuffer(file);
        });
    }

    extractDicomData(dataSet, file) {
        const data = {
            fileName: file.name,
            fileSize: file.size
        };

        // 患者信息
        data.patientName = this.getString(dataSet, 'x00100010') || '';
        data.patientId = this.getString(dataSet, 'x00100020') || '';
        data.patientBirthDate = this.getString(dataSet, 'x00100030') || '';
        data.patientSex = this.getString(dataSet, 'x00100040') || '';

        // 检查信息
        data.studyInstanceUID = this.getString(dataSet, 'x0020000d') || '';
        data.studyDate = this.getString(dataSet, 'x00080020') || '';
        data.studyTime = this.getString(dataSet, 'x00080030') || '';
        data.studyDescription = this.getString(dataSet, 'x00081030') || '';

        // 序列信息
        data.seriesInstanceUID = this.getString(dataSet, 'x0020000e') || '';
        data.seriesNumber = this.getNumber(dataSet, 'x00200011') || 0;
        data.seriesDescription = this.getString(dataSet, 'x0008103e') || '';
        data.modality = this.getString(dataSet, 'x00080060') || '';

        // 图像信息
        data.instanceNumber = this.getNumber(dataSet, 'x00200013') || 0;
        data.imagePosition = this.getNumberArray(dataSet, 'x00200032') || [0, 0, 0];
        data.imageOrientation = this.getNumberArray(dataSet, 'x00200037') || [1, 0, 0, 0, 1, 0];
        data.pixelSpacing = this.getNumberArray(dataSet, 'x00280030') || [1, 1];
        data.sliceThickness = this.getNumber(dataSet, 'x00180050') || 0;
        data.sliceLocation = this.getNumber(dataSet, 'x00201041') || 0;

        // 图像参数
        data.rows = this.getNumber(dataSet, 'x00280010') || 0;
        data.columns = this.getNumber(dataSet, 'x00280011') || 0;
        data.bitsAllocated = this.getNumber(dataSet, 'x00280100') || 16;
        data.bitsStored = this.getNumber(dataSet, 'x00280101') || 16;
        data.highBit = this.getNumber(dataSet, 'x00280102') || 15;
        data.pixelRepresentation = this.getNumber(dataSet, 'x00280103') || 0;
        data.samplesPerPixel = this.getNumber(dataSet, 'x00280002') || 1;
        data.photometricInterpretation = this.getString(dataSet, 'x00280004') || '';

        // 设备和曝光参数
        data.kvp = this.getNumber(dataSet, 'x00180060'); // kVp
        data.xRayTubeCurrent = this.getNumber(dataSet, 'x00181151'); // X-Ray Tube Current
        data.exposureTime = this.getNumber(dataSet, 'x00181150'); // Exposure Time
        data.exposure = this.getNumber(dataSet, 'x00181152'); // Exposure

        // 窗宽窗位
        data.windowWidth = this.getNumber(dataSet, 'x00281051');
        data.windowCenter = this.getNumber(dataSet, 'x00281050');
        
        // 如果没有窗宽窗位信息，根据图像类型设置默认值
        if (!data.windowWidth || !data.windowCenter) {
            const modality = data.modality || '';
            if (modality === 'CT') {
                data.windowWidth = data.windowWidth || 400;
                data.windowCenter = data.windowCenter || 40;
            } else if (modality === 'MR') {
                data.windowWidth = data.windowWidth || 1000;
                data.windowCenter = data.windowCenter || 500;
            } else if (modality === 'CR' || modality === 'DX') {
                data.windowWidth = data.windowWidth || 2000;
                data.windowCenter = data.windowCenter || 1000;
            } else {
                // 通用默认值
                data.windowWidth = data.windowWidth || 1000;
                data.windowCenter = data.windowCenter || 500;
            }
        }

        // 像素数据
        data.pixelDataElement = dataSet.elements.x7fe00010;

        return data;
    }

    createImageData(dataSet) {
        try {
            const rows = this.getNumber(dataSet, 'x00280010');
            const columns = this.getNumber(dataSet, 'x00280011');
            const bitsAllocated = this.getNumber(dataSet, 'x00280100') || 16;
            const pixelRepresentation = this.getNumber(dataSet, 'x00280103') || 0;
            const samplesPerPixel = this.getNumber(dataSet, 'x00280002') || 1;

            let finalRows = rows;
            let finalColumns = columns;

            if (!finalRows || !finalColumns) {
                const rowsElement = dataSet.elements.x00280010;
                const columnsElement = dataSet.elements.x00280011;
                
                if (!finalRows && rowsElement && rowsElement.length > 0) {
                    finalRows = this.parseElementDirectly(dataSet, rowsElement);
                }
                
                if (!finalColumns && columnsElement && columnsElement.length > 0) {
                    finalColumns = this.parseElementDirectly(dataSet, columnsElement);
                }
                
                if (!finalRows || !finalColumns) {
                    throw new Error(`无效的图像尺寸: rows=${finalRows}, columns=${finalColumns}`);
                }
            }

            const pixelDataElement = dataSet.elements.x7fe00010;
            if (!pixelDataElement) {
                throw new Error('未找到像素数据');
            }

            const pixelData = new Uint8Array(dataSet.byteArray, pixelDataElement.dataOffset, pixelDataElement.length);
            
            // 优化像素值范围计算
            const { minPixelValue, maxPixelValue } = this.calculatePixelRange(pixelData, bitsAllocated, pixelRepresentation);
            
            return {
                rows: finalRows,
                columns: finalColumns,
                bitsAllocated,
                pixelRepresentation,
                samplesPerPixel,
                pixelData,
                minPixelValue,
                maxPixelValue
            };
        } catch (error) {
            console.error('创建图像数据失败:', error);
            return null;
        }
    }

    // 新增：优化的像素值范围计算方法
    calculatePixelRange(pixelData, bitsAllocated, pixelRepresentation) {
        let minPixelValue = Infinity;
        let maxPixelValue = -Infinity;
        
        // 使用更高效的采样策略
        const totalPixels = pixelData.length / (bitsAllocated === 16 ? 2 : 1);
        const sampleSize = Math.min(10000, totalPixels);
        const step = Math.max(1, Math.floor(totalPixels / sampleSize));
        
        // 使用 TypedArray 视图来优化内存访问
        const view = new DataView(pixelData.buffer, pixelData.byteOffset, pixelData.byteLength);
        
        for (let i = 0; i < pixelData.length; i += step * (bitsAllocated === 16 ? 2 : 1)) {
            let pixelValue;
            
            if (bitsAllocated === 16) {
                if (i + 1 < pixelData.length) {
                    pixelValue = view.getUint16(i, true); // little endian
                    
                    if (pixelRepresentation === 1 && pixelValue > 32767) {
                        pixelValue -= 65536;
                    }
                } else {
                    continue;
                }
            } else {
                pixelValue = view.getUint8(i);
            }
            
            minPixelValue = Math.min(minPixelValue, pixelValue);
            maxPixelValue = Math.max(maxPixelValue, pixelValue);
        }
        
        if (minPixelValue === Infinity || maxPixelValue === -Infinity) {
            minPixelValue = 0;
            maxPixelValue = Math.pow(2, bitsAllocated) - 1;
        }
        
        return { minPixelValue, maxPixelValue };
    }

    // 直接解析元素数据的辅助方法
    parseElementDirectly(dataSet, element) {
        try {
            if (!element || !dataSet.byteArray) return null;
            
            const view = new DataView(dataSet.byteArray.buffer, element.dataOffset, element.length);
            
            // 根据长度判断数据类型
            if (element.length === 2) {
                return view.getUint16(0, true); // little endian
            } else if (element.length === 4) {
                return view.getUint32(0, true); // little endian
            } else if (element.length === 1) {
                return view.getUint8(0);
            }
            
            // 如果是字符串形式的数字
            const bytes = new Uint8Array(dataSet.byteArray, element.dataOffset, element.length);
            let str = '';
            for (let i = 0; i < bytes.length; i++) {
                if (bytes[i] === 0) break;
                str += String.fromCharCode(bytes[i]);
            }
            
            const num = parseInt(str.trim(), 10);
            return isNaN(num) ? null : num;
            
        } catch (error) {
            console.warn('直接解析元素失败:', error);
            return null;
        }
    }

    groupBySeries(dicomFiles, seriesGroups) {
        dicomFiles.forEach(dicomData => {
            const seriesUID = dicomData.seriesInstanceUID || 'unknown';
            
            if (!seriesGroups.has(seriesUID)) {
                seriesGroups.set(seriesUID, {
                    seriesInstanceUID: seriesUID,
                    seriesNumber: dicomData.seriesNumber,
                    seriesDescription: dicomData.seriesDescription,
                    modality: dicomData.modality,
                    studyInstanceUID: dicomData.studyInstanceUID,
                    studyDate: dicomData.studyDate,
                    studyDescription: dicomData.studyDescription,
                    patientName: dicomData.patientName,
                    patientId: dicomData.patientId,
                    images: []
                });
            }
            
            seriesGroups.get(seriesUID).images.push(dicomData);
        });
    }

    sortSeriesImages(series) {
        // 按实例号排序，如果没有实例号则按切片位置排序
        series.images.sort((a, b) => {
            if (a.instanceNumber && b.instanceNumber) {
                return a.instanceNumber - b.instanceNumber;
            } else if (a.sliceLocation !== undefined && b.sliceLocation !== undefined) {
                return a.sliceLocation - b.sliceLocation;
            } else if (a.imagePosition && b.imagePosition) {
                // 按Z坐标排序
                return a.imagePosition[2] - b.imagePosition[2];
            } else {
                // 按文件名排序
                return a.fileName.localeCompare(b.fileName);
            }
        });
    }

    // 辅助方法：获取字符串值
    getString(dataSet, tag) {
        try {
            const element = dataSet.elements[tag];
            if (!element || element.length === 0) {
                return null;
            }

            // 尝试使用 string 方法
            if (typeof dataSet.string === 'function') {
                return dataSet.string(tag);
            }

            // 如果没有 string 方法，尝试直接从字节数组解析
            if (element.dataOffset !== undefined && dataSet.byteArray) {
                const bytes = new Uint8Array(dataSet.byteArray, element.dataOffset, element.length);
                let str = '';
                for (let i = 0; i < bytes.length; i++) {
                    if (bytes[i] === 0) break; // 遇到空字符停止
                    str += String.fromCharCode(bytes[i]);
                }
                return str.trim();
            }
        } catch (error) {
            console.warn(`获取标签 ${tag} 的字符串时出错:`, error);
        }
        
        return null;
    }

    // 辅助方法：获取数值
    getNumber(dataSet, tag) {
        try {
            const element = dataSet.elements[tag];
            if (!element || element.length === 0) {
                // console.log(`标签 ${tag}: 元素不存在或长度为0`);
                return null;
            }

            // console.log(`标签 ${tag}: VR=${element.vr}, length=${element.length}, offset=${element.dataOffset}`);

            // 检查 dataSet 是否有相应的方法
            if (element.vr === 'FL' || element.vr === 'FD') {
                // 浮点数
                if (typeof dataSet.float === 'function') {
                    const value = dataSet.float(tag);
                    // console.log(`标签 ${tag}: 使用 float() 得到 ${value}`);
                    return value;
                } else if (typeof dataSet.floatString === 'function') {
                    const str = dataSet.floatString(tag);
                    const value = str ? parseFloat(str) : null;
                    // console.log(`标签 ${tag}: 使用 floatString() 得到 "${str}" -> ${value}`);
                    return value;
                }
            } else {
                // 整数
                if (typeof dataSet.int === 'function') {
                    const value = dataSet.int(tag);
                    // console.log(`标签 ${tag}: 使用 int() 得到 ${value}`);
                    return value;
                } else if (typeof dataSet.intString === 'function') {
                    const str = dataSet.intString(tag);
                    const value = str ? parseInt(str, 10) : null;
                    // console.log(`标签 ${tag}: 使用 intString() 得到 "${str}" -> ${value}`);
                    return value;
                } else if (typeof dataSet.uint16 === 'function') {
                    const value = dataSet.uint16(tag);
                    // console.log(`标签 ${tag}: 使用 uint16() 得到 ${value}`);
                    return value;
                } else if (typeof dataSet.uint32 === 'function') {
                    const value = dataSet.uint32(tag);
                    // console.log(`标签 ${tag}: 使用 uint32() 得到 ${value}`);
                    return value;
                }
            }

            // 如果上述方法都不可用，尝试从字符串解析
            if (typeof dataSet.string === 'function') {
                const str = dataSet.string(tag);
                if (str) {
                    const num = parseFloat(str);
                    const value = isNaN(num) ? null : num;
                    // console.log(`标签 ${tag}: 使用 string() 得到 "${str}" -> ${value}`);
                    return value;
                }
            }

            // 最后尝试直接从元素数据解析
            if (element.dataOffset !== undefined && dataSet.byteArray) {
                const view = new DataView(dataSet.byteArray.buffer, element.dataOffset, element.length);
                let value = null;
                if (element.length === 2) {
                    value = view.getUint16(0, true); // little endian
                    // console.log(`标签 ${tag}: 直接解析16位得到 ${value}`);
                } else if (element.length === 4) {
                    value = view.getUint32(0, true); // little endian
                    // console.log(`标签 ${tag}: 直接解析32位得到 ${value}`);
                } else if (element.length === 1) {
                    value = view.getUint8(0);
                    // console.log(`标签 ${tag}: 直接解析8位得到 ${value}`);
                } else {
                    // 尝试作为字符串解析
                    const bytes = new Uint8Array(dataSet.byteArray, element.dataOffset, element.length);
                    let str = '';
                    for (let i = 0; i < bytes.length; i++) {
                        if (bytes[i] === 0) break;
                        str += String.fromCharCode(bytes[i]);
                    }
                    const num = parseInt(str.trim(), 10);
                    value = isNaN(num) ? null : num;
                    // console.log(`标签 ${tag}: 作为字符串解析得到 "${str}" -> ${value}`);
                }
                return value;
            }

            console.log(`标签 ${tag}: 所有方法都失败`);

        } catch (error) {
            // console.warn(`获取标签 ${tag} 的数值时出错:`, error);
        }
        
        return null;
    }

    // 辅助方法：获取数值数组
    getNumberArray(dataSet, tag) {
        const element = dataSet.elements[tag];
        if (element && element.length > 0) {
            const str = dataSet.string(tag);
            if (str) {
                return str.split('\\').map(s => parseFloat(s.trim())).filter(n => !isNaN(n));
            }
        }
        return null;
    }

    // 获取序列统计信息
    getSeriesStatistics(series) {
        const stats = {
            imageCount: series.images.length,
            minSliceLocation: Infinity,
            maxSliceLocation: -Infinity,
            sliceThickness: 0,
            pixelSpacing: [0, 0]
        };

        series.images.forEach(image => {
            if (image.sliceLocation !== undefined) {
                stats.minSliceLocation = Math.min(stats.minSliceLocation, image.sliceLocation);
                stats.maxSliceLocation = Math.max(stats.maxSliceLocation, image.sliceLocation);
            }
            
            if (image.sliceThickness) {
                stats.sliceThickness = image.sliceThickness;
            }
            
            if (image.pixelSpacing) {
                stats.pixelSpacing = image.pixelSpacing;
            }
        });

        if (stats.minSliceLocation === Infinity) {
            stats.minSliceLocation = 0;
            stats.maxSliceLocation = 0;
        }

        return stats;
    }

    // 检查是否为DICOM文件
    isDicomFile(byteArray) {
        // 检查文件大小
        if (byteArray.length < 132) {
            return false;
        }
        
        // 检查DICOM前导码（128字节的0x00，然后是"DICM"）
        const hasDicomPreamble = 
            byteArray[128] === 0x44 && // 'D'
            byteArray[129] === 0x49 && // 'I'
            byteArray[130] === 0x43 && // 'C'
            byteArray[131] === 0x4D;   // 'M'
        
        if (hasDicomPreamble) {
            return true;
        }
        
        // 检查是否为没有前导码的DICOM文件
        // 查找常见的DICOM标签在文件开头
        try {
            // 检查前几个字节是否包含DICOM标签模式
            for (let i = 0; i < Math.min(512, byteArray.length - 8); i += 2) {
                // 检查是否为有效的DICOM标签格式 (group, element)
                const group = (byteArray[i + 1] << 8) | byteArray[i];
                const element = (byteArray[i + 3] << 8) | byteArray[i + 2];
                
                // 检查一些常见的DICOM标签
                if ((group === 0x0008 && (element === 0x0000 || element === 0x0005 || element === 0x0060)) ||
                    (group === 0x0010 && (element === 0x0010 || element === 0x0020)) ||
                    (group === 0x0020 && (element === 0x000D || element === 0x000E)) ||
                    (group === 0x0028 && (element === 0x0010 || element === 0x0011))) {
                    return true;
                }
            }
        } catch (error) {
            // 如果检查过程中出错，继续其他检查
        }
        
        return false;
    }

    // 验证DICOM文件
    validateDicomFile(dataSet) {
        // 检查必要的DICOM标签
        const requiredTags = [
            'x00280010', // Rows
            'x00280011', // Columns
            'x7fe00010'  // Pixel Data
        ];

        for (const tag of requiredTags) {
            if (!dataSet.elements[tag]) {
                throw new Error(`缺少必要的DICOM标签: ${tag}`);
            }
        }

        return true;
    }

    // 分析序列并推荐最佳窗宽窗位
    analyzeOptimalWindowLevel(series) {
        if (!series || !series.images || series.images.length === 0) {
            return { windowWidth: 1000, windowCenter: 500, preset: 'default' };
        }

        const firstImage = series.images[0];
        const modality = series.modality || '';
        const seriesDescription = (series.seriesDescription || '').toLowerCase();
        
        // console.log(`分析序列窗宽窗位: 模态=${modality}, 描述="${seriesDescription}"`);

        // 1. 如果DICOM文件中已有窗宽窗位信息，优先使用
        if (firstImage.windowWidth && firstImage.windowCenter) {
            // console.log(`使用DICOM文件中的窗宽窗位: ${firstImage.windowWidth}/${firstImage.windowCenter}`);
            return {
                windowWidth: firstImage.windowWidth,
                windowCenter: firstImage.windowCenter,
                preset: 'dicom'
            };
        }

        // 2. 根据像素值范围计算
        let globalMin = Infinity;
        let globalMax = -Infinity;
        let validImageCount = 0;

        // 采样部分图像来计算像素值范围
        const sampleImages = series.images.slice(0, Math.min(5, series.images.length));
        
        for (const image of sampleImages) {
            if (image.imageData && image.imageData.minPixelValue !== undefined && image.imageData.maxPixelValue !== undefined) {
                globalMin = Math.min(globalMin, image.imageData.minPixelValue);
                globalMax = Math.max(globalMax, image.imageData.maxPixelValue);
                validImageCount++;
            }
        }

        console.log(`像素值范围分析: min=${globalMin}, max=${globalMax}, 有效图像=${validImageCount}`);

        // 3. 根据模态和序列描述选择预设
        let windowWidth, windowCenter, preset;

        if (modality === 'CT') {
            // CT图像的窗宽窗位预设
            if (seriesDescription.includes('lung') || seriesDescription.includes('chest')) {
                // 肺窗
                windowWidth = 1500;
                windowCenter = -600;
                preset = 'lung';
            } else if (seriesDescription.includes('bone')) {
                // 骨窗
                windowWidth = 2000;
                windowCenter = 300;
                preset = 'bone';
            } else if (seriesDescription.includes('brain') || seriesDescription.includes('head')) {
                // 脑窗
                windowWidth = 80;
                windowCenter = 40;
                preset = 'brain';
            } else if (seriesDescription.includes('abdomen') || seriesDescription.includes('liver')) {
                // 腹部窗
                windowWidth = 350;
                windowCenter = 50;
                preset = 'abdomen';
            } else {
                // CT软组织窗（默认）
                windowWidth = 400;
                windowCenter = 40;
                preset = 'soft_tissue';
            }
        } else if (modality === 'MR') {
            // MR图像的窗宽窗位
            if (seriesDescription.includes('t1')) {
                windowWidth = 600;
                windowCenter = 300;
                preset = 't1';
            } else if (seriesDescription.includes('t2')) {
                windowWidth = 800;
                windowCenter = 400;
                preset = 't2';
            } else if (seriesDescription.includes('flair')) {
                windowWidth = 1000;
                windowCenter = 500;
                preset = 'flair';
            } else {
                // MR默认
                windowWidth = 1000;
                windowCenter = 500;
                preset = 'mr_default';
            }
        } else if (modality === 'CR' || modality === 'DX') {
            // X光图像
            windowWidth = 2000;
            windowCenter = 1000;
            preset = 'xray';
        } else if (modality === 'US') {
            // 超声图像
            windowWidth = 256;
            windowCenter = 128;
            preset = 'ultrasound';
        } else {
            // 其他模态，根据像素值范围自动计算
            if (globalMin !== Infinity && globalMax !== -Infinity) {
                windowWidth = globalMax - globalMin;
                windowCenter = (globalMax + globalMin) / 2;
                preset = 'auto_range';
            } else {
                // 通用默认值
                windowWidth = 1000;
                windowCenter = 500;
                preset = 'default';
            }
        }

        // 4. 如果有像素值范围信息，进行微调
        if (globalMin !== Infinity && globalMax !== -Infinity && preset !== 'auto_range') {
            // 检查预设值是否合理，如果不合理则调整
            const pixelRange = globalMax - globalMin;
            const pixelCenter = (globalMax + globalMin) / 2;
            
            // 如果预设窗宽远大于像素范围，调整窗宽
            if (windowWidth > pixelRange * 3) {
                windowWidth = Math.max(pixelRange, windowWidth * 0.5);
                console.log(`调整窗宽以适应像素范围: ${windowWidth}`);
            }
            
            // 如果预设窗位远离像素中心，调整窗位
            if (Math.abs(windowCenter - pixelCenter) > pixelRange) {
                windowCenter = pixelCenter;
                console.log(`调整窗位以适应像素中心: ${windowCenter}`);
            }
        }

        console.log(`推荐窗宽窗位: ${windowWidth}/${windowCenter} (预设: ${preset})`);

        return {
            windowWidth: Math.round(windowWidth),
            windowCenter: Math.round(windowCenter),
            preset,
            pixelRange: globalMin !== Infinity ? { min: globalMin, max: globalMax } : null
        };
    }

    // 获取常用窗宽窗位预设
    getWindowLevelPresets(modality) {
        const presets = {
            CT: [
                { name: '软组织', windowWidth: 400, windowCenter: 40 },
                { name: '肺窗', windowWidth: 1500, windowCenter: -600 },
                { name: '骨窗', windowWidth: 2000, windowCenter: 300 },
                { name: '脑窗', windowWidth: 80, windowCenter: 40 },
                { name: '腹部', windowWidth: 350, windowCenter: 50 },
                { name: '纵隔', windowWidth: 350, windowCenter: 50 }
            ],
            MR: [
                { name: 'T1加权', windowWidth: 600, windowCenter: 300 },
                { name: 'T2加权', windowWidth: 800, windowCenter: 400 },
                { name: 'FLAIR', windowWidth: 1000, windowCenter: 500 },
                { name: 'DWI', windowWidth: 1000, windowCenter: 500 }
            ],
            CR: [
                { name: '胸部', windowWidth: 2000, windowCenter: 1000 },
                { name: '腹部', windowWidth: 1500, windowCenter: 800 },
                { name: '骨骼', windowWidth: 2500, windowCenter: 1200 }
            ],
            DX: [
                { name: '胸部', windowWidth: 2000, windowCenter: 1000 },
                { name: '腹部', windowWidth: 1500, windowCenter: 800 },
                { name: '骨骼', windowWidth: 2500, windowCenter: 1200 }
            ]
        };

        return presets[modality] || [
            { name: '默认', windowWidth: 1000, windowCenter: 500 }
        ];
    }
} 